package com.ddstation.onsitelaw.controller;

import com.ddstation.onsitelaw.entity.DtHealthManageInstitutionEntity;
import com.ddstation.onsitelaw.entity.DtSupervisorEnforcementEntity;
import com.ddstation.onsitelaw.entity.MaInvsViolationMessageEntity;
import com.ddstation.onsitelaw.model.AccountModel;
import com.ddstation.onsitelaw.model.AuditPrescriptionModel;
import com.ddstation.onsitelaw.service.AuditPrescriptionService;
import com.ddstation.onsitelaw.service.ViolationRecordService;
import com.ddstation.onsitelaw.utils.DateUtil;
import com.ddstation.onsitelaw.utils.PageResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author 忆秋枫
 */
@Controller
public class PrescriptionAuditController {

    private static final Logger logger = LoggerFactory.getLogger(PrescriptionAuditController.class);
    @Inject
    private AuditPrescriptionService auditPrescriptionService;
    @Inject
    private ViolationRecordService violationRecordService;

    /**
     * 跳转处方审核页
     */
    @RequestMapping(value = "prescriptionAudit")
    String drugsQuery(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", -1);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
        }
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        // 获取当天
        Calendar cale = Calendar.getInstance();
        String lastday = format.format(cale.getTime());
        //取开始时间 0：今日  1：本周
        String firstday = DateUtil.getFirstday(1);
        // 开始时间
        model.addAttribute("dtFrom", firstday);
        // 当天
        model.addAttribute("dtTo", lastday);

        HashMap paramMap = new HashMap();
        paramMap.put("province", account.getManageInstitutionEntity().getProvince());
        paramMap.put("city", account.getManageInstitutionEntity().getCity());
        List<AccountModel> personnels = auditPrescriptionService.selectPersonnel(paramMap);
        model.addAttribute("personnels", personnels);

        List<MaInvsViolationMessageEntity> violationMessageList = violationRecordService.selectList();
        if (ObjectUtils.isEmpty(violationMessageList)) {
            throw new RuntimeException("master表【ma_invs_violation_message】没有数据！");
        }
        model.addAttribute("violationMessageList", violationMessageList);
        return "prescriptionAudit";
    }


    /**
     * 未审核处方查询接口
     *
     * @return
     */
    @RequestMapping(value = "prescriptionAudit/notReviewedList", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> notReviewedList(
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam String uploaderId,
            @RequestParam String institutionName,
            @RequestParam String pageNum,
            @RequestParam String pageSize,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<>();
        ret.put("errcode", -1);
        ret.put("errMsg", "系统出错，请稍后再试！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            ret.put("code", -1);
            ret.put("msg", "登录状态已失效，请重新登录!");
        }
        List<String> healthManageInstitutionIds = null;
        if (account.getRoleId() == 1) {
            List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
            healthManageInstitutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
        }
        if (account.getRoleId() == 2) {
            List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
            healthManageInstitutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
        }
        HashMap paramMap = new HashMap();
        paramMap.put("dtFrom", dtFrom);
        paramMap.put("dtTo", dtTo);
        paramMap.put("uploaderId", uploaderId);
        paramMap.put("institutionName", institutionName);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        paramMap.put("institutionIds", healthManageInstitutionIds);

        PageResult pageResult = auditPrescriptionService.selectNotAuditList(paramMap);
        ret.put("notReviewedList", pageResult.getRows());
        ret.put("total", pageResult.getTotal());
        ret.put("pages", pageResult.getPages());
        ret.put("errcode", 0);
        ret.put("errMsg", "请求成功！");
        return ret;
    }


    /**
     * 审核处方
     *
     * @return
     */
    @RequestMapping(value = "prescriptionAudit/auditPrescription", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> auditPrescription(
            @RequestBody AuditPrescriptionModel auditPrescriptionModel,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<>();
        ret.put("errcode", -1);
        ret.put("errMsg", "系统出错，请稍后再试！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            ret.put("code", -1);
            ret.put("msg", "登录状态已失效，请重新登录!");
        }
        auditPrescriptionModel.setInvsInstitutionId(account.getInstitutionId());
        auditPrescriptionModel.setAuditName(account.getName());
        auditPrescriptionModel.setAuditTm(new Date());
        auditPrescriptionModel.setAuditId(account.getSupervisorId());
        if (!ObjectUtils.isEmpty(auditPrescriptionModel.getMsgIds())) {
            String[] msgIds = auditPrescriptionModel.getMsgIds();
            for (int i = 0; i < msgIds.length; i++) {
                auditPrescriptionModel.setMsgId(msgIds[i]);
                violationRecordService.insertViolation(auditPrescriptionModel);
            }
        }
        auditPrescriptionService.updateAuditPrescription(auditPrescriptionModel);
        ret.put("errcode", 0);
        ret.put("errMsg", "请求成功！");
        return ret;
    }


    /**
     * 未审核处方查询接口
     *
     * @return
     */
    @RequestMapping(value = "prescriptionAudit/reviewedList", method = RequestMethod.POST)
    public @ResponseBody
    Map<String, Object> reviewedList(
            @RequestParam String dtFrom,
            @RequestParam String dtTo,
            @RequestParam String auditId,
            @RequestParam String auditResult,
            @RequestParam String institutionName,
            @RequestParam String pageNum,
            @RequestParam String pageSize,
            HttpSession session) {
        Map<String, Object> ret = new HashMap<>();
        ret.put("errcode", -1);
        ret.put("errMsg", "系统出错，请稍后再试！");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            ret.put("code", -1);
            ret.put("msg", "登录状态已失效，请重新登录!");
        }
        List<String> healthManageInstitutionIds = null;
        if (account.getRoleId() == 1) {
            List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
            healthManageInstitutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
        }
        if (account.getRoleId() == 2) {
            List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
            healthManageInstitutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
        }
        HashMap paramMap = new HashMap();
        paramMap.put("dtFrom", dtFrom);
        paramMap.put("dtTo", dtTo);
        paramMap.put("auditId", auditId);
        paramMap.put("auditResult", auditResult);
        paramMap.put("institutionName", institutionName);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        paramMap.put("institutionIds", healthManageInstitutionIds);

        PageResult pageResult = auditPrescriptionService.selectAuditList(paramMap);
        ret.put("reviewedList", pageResult.getRows());
        ret.put("total", pageResult.getTotal());
        ret.put("pages", pageResult.getPages());
        ret.put("errcode", 0);
        ret.put("errMsg", "请求成功！");
        return ret;
    }


    /**
     * 跳转模板设置管理页
     */
    @RequestMapping(value = "templateSet")
    String accountManage(HttpSession session, Model model) {
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            //session无登录信息返回登录页
            model.addAttribute("code", -1);
            model.addAttribute("msg", "登录状态已失效，请重新登录!");
            return "accountManage";
        }
        return "templateSet";
    }


    @RequestMapping("prescriptionAudit/templates")
    @ResponseBody
    Map<String, Object> templateList(
            HttpSession session,
            @RequestParam String institutionalName,
            @RequestParam String templateName,
            @RequestParam String templateSign,
            @RequestParam String pageNum,
            @RequestParam String pageSize) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        List<String> healthManageInstitutionIds = null;
        if (account.getRoleId() == 1) {
            List<DtHealthManageInstitutionEntity> healthManageList = account.getDtHealthManageInstitutionEntityList();
            healthManageInstitutionIds = healthManageList.stream().map(i -> i.getId()).collect(Collectors.toList());
        }
        if (account.getRoleId() == 2) {
            List<DtSupervisorEnforcementEntity> supervisorEnforcements = account.getEnforcementList();
            healthManageInstitutionIds = supervisorEnforcements.stream().map(i -> i.getHealthManageId()).collect(Collectors.toList());
        }
        HashMap paramMap = new HashMap();
        paramMap.put("institutionIds", healthManageInstitutionIds);
        paramMap.put("institutionalName", institutionalName);
        paramMap.put("templateName", templateName);
        paramMap.put("templateSign", templateSign);
        paramMap.put("pageNum", pageNum);
        paramMap.put("pageSize", pageSize);
        PageResult pageResult = auditPrescriptionService.selectTemplateList(paramMap);
        map.put("templateList", pageResult.getRows());
        map.put("totalNum", pageResult.getTotal());
        map.put("pages", pageResult.getPages());
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }


    @RequestMapping("prescriptionAudit/updateTemplateSign")
    @ResponseBody
    Map<String, Object> updateTemplateSign(
            HttpSession session,
            @RequestParam String institutionId,
            @RequestParam String templateSign) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        auditPrescriptionService.updateTemplateSign(institutionId, templateSign);
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }


    @RequestMapping("prescriptionAudit/deleteAuditPrescription")
    @ResponseBody
    Map<String, Object> deleteAuditPrescription(
            HttpSession session,
            @RequestParam Integer reviewedId) {
        Map<String, Object> map = new HashMap<>();
        map.put("errCode", 0);
        map.put("errMsg", "服务器繁忙，请稍后再试。");
        //获取session登录信息
        AccountModel account = (AccountModel) session.getAttribute("account");
        if (account == null || account.getSupervisorId() == null) {
            map.put("errCode", -1);
            return map;
        }
        auditPrescriptionService.deleteAuditPrescription(reviewedId);
        map.put("errCode", 1);
        map.put("errMsg", "成功");
        return map;
    }

}